package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.model.domain.DmcControllerCardBind;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.dto.card.ControllerCardBindDto;
import com.csun.cmny.provider.model.dto.device.DevicePageQuery;
import com.csun.cmny.provider.model.dto.device.DmcEditDeviceDto;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.card.ControllerCardVo;
import com.csun.cmny.provider.model.vo.rfid.DmcRfidReaderVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcControllerCardBindService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.validator.DmcDeviceEditValidator;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-12-05 15:17
 * @Description:
 */
@RestController
@RequestMapping(value = "/controllerCard", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcControllerCardController extends BaseController {

    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private DmcControllerCardBindService dmcControllerCardBindService;

    /**
     * 查询没有绑定门禁控制卡的门禁读卡器
     *
     * 注意：门禁读卡器需要先绑定位置
     *
     * @return  the wrapper
     */
    @RequestMapping(value = "/queryNotBindRfidReader", method = RequestMethod.POST)
    public Wrapper queryNotBindRfidReader() {

        List<DmcRfidReaderVo> dmcRfidReaderVoList = dmcControllerCardBindService
                .queryNotBindRfidReader(getLoginAuthDto().getGroupId());

       // return WrapMapper.ok(dmcRfidReaderVoList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),dmcRfidReaderVoList);
    }


    /**
     * 查询列表
     */
    @PostMapping(value = "/queryNewListWithPage")
    public Wrapper queryNewListWithPage(@RequestBody DevicePageQuery devicePageQuery) {

        devicePageQuery.setGroupId(getLoginAuthDto().getGroupId());
        devicePageQuery.setDeviceType(DmcDeviceTypeEnum.CONTROLLER_CARD.getIndex());

        List<ControllerCardVo> controllerCardVoList = dmcControllerCardBindService
                .queryNewListWithPage(devicePageQuery);

        PageInfo pageInfo = new PageInfo<>(controllerCardVoList);
        pageInfo.setTotal(controllerCardVoList.size());

        // return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 查询列表
     */
    @PostMapping(value = "/queryListWithPage")
    public Wrapper queryListWithPage(@RequestBody DevicePageQuery devicePageQuery) {

        devicePageQuery.setGroupId(getLoginAuthDto().getGroupId());
        devicePageQuery.setDeviceType(DmcDeviceTypeEnum.CONTROLLER_CARD.getIndex());

        PageInfo pageInfo = dmcControllerCardBindService
                .queryListWithPage(devicePageQuery);

//        PageInfo pageInfo = new PageInfo<>(controllerCardVoList);
//        pageInfo.setTotal(controllerCardVoList.size());

       // return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 添加
     */
    @ValidateAnnotation
    @PostMapping(value = "/add")
    public Wrapper add(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();

        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CONTROLLER_CARD.getIndex());

        Integer result = dmcDeviceService.addDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
//            CsunGatewayData csunGatewayData = new CsunGatewayData();
//            csunGatewayData.setDeviceId(dmcDevice.getId());
//            csunGatewayData.setDeviceNo(dmcDevice.getDeviceNo());
//
//            redisTemplate.opsForValue().set(RedisKeyUtil.getCsunGatewayKey(dmcDevice.getDeviceNo()),
//                    csunGatewayData);
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 修改
     */
    @ValidateAnnotation
    @PostMapping(value = "/edit")
    public Wrapper edit(@Validated(value = {DmcDeviceEditValidator.class})
                            @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {


        DmcDevice dmcDevice = new DmcDevice();
        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CONTROLLER_CARD.getIndex());

//        DmcDevice dmcDeviceOld = dmcDeviceService.selectByKey(dmcEditDeviceDto.getId());

        Integer result = dmcDeviceService.editDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 判断是否有修改deviceNo
//            if (!dmcDeviceOld.getDeviceNo().equals(dmcEditDeviceDto.getDeviceNo())) {
//                // 删除旧的redisKey(deviceNo)
//                String redisKey = RedisKeyUtil.getCsunGatewayKey(dmcDeviceOld.getDeviceNo());
//                CsunGatewayData csunGatewayData = (CsunGatewayData) redisTemplate.opsForValue().get(redisKey);
//                if (PublicUtil.isNotEmpty(csunGatewayData)) {
//                    // 删除旧的
//                    redisTemplate.delete(redisKey);
//                    // 添加新的
//                    csunGatewayData.setDeviceNo(dmcEditDeviceDto.getDeviceNo());
//                    csunGatewayData.setStatus(DeviceStatusEnum.OFFLINE.getKey());   // 设备下线
//                    redisKey = RedisKeyUtil.getCsunGatewayKey(dmcEditDeviceDto.getDeviceNo());
//                    redisTemplate.opsForValue().set(redisKey, csunGatewayData);
//                }
//            }
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 删除
     */
    @PostMapping(value = "/deleteById/{id}")
    public Wrapper deleteById(@PathVariable Long id) {

        Integer result = dmcControllerCardBindService.deleteById(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 删除redisKey(deviceNo)
//            redisTemplate.delete(RedisKeyUtil.getCsunGatewayKey(dmcDeviceOld.getDeviceNo()));
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 绑定
     */
    @PostMapping(value = "/bind")
    public Wrapper bind(@RequestBody ControllerCardBindDto controllerCardBindDto) {

        Integer result = dmcControllerCardBindService.bind(controllerCardBindDto);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }


    /**
     * 解绑
     */
    @PostMapping(value = "/untied/{id}")
    public Wrapper untied(@PathVariable Long id) {

        DmcControllerCardBind dmcControllerCardBind = new DmcControllerCardBind();
        dmcControllerCardBind.setControllerCardId(id);
        Integer result = dmcControllerCardBindService.untied(dmcControllerCardBind);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 查询门禁卡组信息
     */
    @PostMapping(value = "/queryControllerCardByDeviceNo")
    public Wrapper queryControllerCardByDeviceNo(String deviceNo) {

        ControllerCardVo controllerCardVo = dmcControllerCardBindService.queryControllerCardByDeviceNo(deviceNo);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,
                cmnyMessageSource.getMessage("operation.success", null),
                controllerCardVo);
    }
}
